//
//  KeepCallsController.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/12/22.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "KeepCallsController.h"
#import "KeepCallsTopCell.h"
#import "KeepCallsPhoneCell.h"
#import "KeepCallsSelectCell.h"
#import "KeepCallsPayCell.h"
#import "KeepCallSectionHeader.h"
#import "KeepCallBottomView.h"
#import "SelectedListView.h"
#import <LEEAlert/LEEAlert.h>
#import "GoodsDetailModel.h"


#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>

#import "PayFaildJumpVC.h"
#import "PaySuccessJumpVC.h"

@interface KeepCallsController ()

@property (nonatomic, strong) KeepCallBottomView *footerView;


@property (nonatomic, strong) GoodsDetailModel *dataModel;
@property (nonatomic, strong) NSString *payTag;


/** <#note#> */
@property (nonatomic, strong) NSString *out_trade_no;
@end

@implementation KeepCallsController


- (KeepCallBottomView *)footerView{
    
    if (!_footerView) {
        
        KeepCallBottomView *temp = (KeepCallBottomView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([KeepCallBottomView class]) owner:nil options:nil].firstObject;
        
        [temp.topBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        [temp.topBtn setTitle:@"立即支付" forState:UIControlStateHighlighted];
        
        [temp.topBtn addTarget:self action:@selector(gotoOderPage) forControlEvents:UIControlEventTouchUpInside];

        _footerView = temp;
        
        [self.view addSubview:temp];
        
    }
    
    return _footerView;
}



- (void)gotoOderPage{
    
    
    [self.view endEditing:YES];
    
    if (self.dataModel.phoneNumber == nil) {
        
        [SVProgressHUD showInfoWithStatus:@"请填写手机号"];
        
        return;
    }
    
    
   BOOL isPhoneNumber = [[NetworkTools shareNetworkTools]isPhoneNumber:self.dataModel.phoneNumber];
    
    if (!isPhoneNumber) {
        
        [SVProgressHUD showInfoWithStatus:@"手机号格式错误"];

        return;
    }
    
        NSMutableString *strM = [NSMutableString string];
        [strM appendString:self.dataModel.selectSkuModel.sku_id];
        [strM appendString:@":"];
        [strM appendString:@"1"];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"goods_sku_list"] = strM;
    parameters[@"user_telephone"] = self.dataModel.phoneNumber;
    parameters[@"uid"] = myViewModel.user.uid;

    
    
    [SVProgressHUD showWithStatus:@"订单确认中..."];
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"Order/virtualOrderCreate" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            
            [weakSelf lastPayWitPayment:responseObject[@"data"][@"pay_rmb"] outTradeNo:responseObject[@"data"][@"out_trade_no"]];
            
            weakSelf.out_trade_no = responseObject[@"data"][@"out_trade_no"];
            
            
        } else {
            
            
            [SVProgressHUD showInfoWithStatus:error.domain];
        }
    }];
    


}





- (void)lastPayWitPayment:(NSString *)payment outTradeNo:(NSString *)trade{
    //    ?out_trade_no=&pay_type=2&payment=0.01
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"payment"] = payment;
    parameters[@"out_trade_no"] = trade;
    
    if ([self.dataModel.alipay isEqualToString:@"1"]) {
        
        parameters[@"pay_type"] = @"2";
        
        [self AlipayPayWith:parameters];
        
    } else {
        
        parameters[@"pay_type"] = @"1";
        
        [self wachatPay:parameters];
        
        
    }
    
   
    
    
}





- (void)AlipayPayWith:(NSMutableDictionary *)parameters{
    
    
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            [[AlipaySDK defaultService] payOrder:responseObject[@"data"] fromScheme:@"com.beisheng.feifubao" callback:^(NSDictionary *resultDic) {
                
                
                NSLog(@"reslut = %@",resultDic);
                
            }];
            
            
        } else {
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    
}




- (void)wachatPay:(NSMutableDictionary *)parameters{
    
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
//            MYJSONSTR;
            
            [self WXPayWithDic:responseObject[@"data"]];
            
            
        } else {
            
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    
    
    
    
    
}



- (void)WXPayWithDic:(NSDictionary *)dic{
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = dic[@"appid"];
    
    // 商家id，在注册的时候给的
    req.partnerId = dic[@"partnerid"];
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = dic[@"prepayid"];
    
    // 根据财付通文档填写的数据和签名
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = dic[@"pkg"];
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = dic[@"noncestr"];
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = dic[@"timestamp"];
    
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = dic[@"sign"];
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"话费充值";
    
    self.view.backgroundColor = viewBgGrey;
    
    self.payTag = @"0";
    
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeepCallsTopCell class]) bundle:nil] forCellReuseIdentifier:[KeepCallsTopCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeepCallsPhoneCell class]) bundle:nil] forCellReuseIdentifier:[KeepCallsPhoneCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeepCallsSelectCell class]) bundle:nil] forCellReuseIdentifier:[KeepCallsSelectCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeepCallsPayCell class]) bundle:nil] forCellReuseIdentifier:[KeepCallsPayCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeepCallSectionHeader class]) bundle:nil] forHeaderFooterViewReuseIdentifier:[KeepCallSectionHeader identifierStr]];
    
    MJWeakSelf
    self.plainTableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [weakSelf.plainTableView.mj_header beginRefreshing];
    
   
    self.plainTableView.tableFooterView = self.footerView;
    
    
    self.footerView.hidden = YES;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidSuccessNotification) name:WXApiDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidFailNotification) name:WXApiDidFailNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidSuccessNotification) name:AlipayDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidFailNotification) name:AlipayDidFailNotification object:nil];
    
}


- (void)WXApiDidSuccessNotification{
    
    if ([self.payTag isEqualToString:@"0"]) {
        self.payTag = @"1";
        PaySuccessJumpVC *jump = [[PaySuccessJumpVC alloc]init];
        
        jump.order_id = self.out_trade_no;
        
        [self.navigationController pushViewController:jump animated:YES];
    }
    
    

    
}


- (void)WXApiDidFailNotification{
    
    if ([self.payTag isEqualToString:@"0"]) {
        self.payTag = @"1";
        PayFaildJumpVC *jump = [[PayFaildJumpVC alloc]init];
        jump.order_id = self.out_trade_no;
        [self.navigationController pushViewController:jump animated:YES];
    }
    
    
   
    
}

- (void)AlipayDidSuccessNotification{
    
    
    if ([self.payTag isEqualToString:@"0"]) {
        self.payTag = @"1";
        PaySuccessJumpVC *jump = [[PaySuccessJumpVC alloc]init];
        
        jump.order_id = self.out_trade_no;
        
        [self.navigationController pushViewController:jump animated:YES];
    }
    
    
}


- (void)AlipayDidFailNotification{
    
    if ([self.payTag isEqualToString:@"0"]) {
        self.payTag = @"1";
        PayFaildJumpVC *jump = [[PayFaildJumpVC alloc]init];
        jump.order_id = self.out_trade_no;
        [self.navigationController pushViewController:jump animated:YES];
    }
    
    
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}





- (void)loadData{
    
   
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    if (myViewModel.userIsLogin) {
        
        parameters[@"uid"] = myViewModel.user.uid;
        
    }
    
    parameters[@"goodsId"] = @"4";
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"Good/getGoodsDetail" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
      
            
//                        MYJSONSTR
            
            weakSelf.dataModel = [GoodsDetailModel mj_objectWithKeyValues:responseObject[@"data"]];
            
            weakSelf.dataModel.tag = @"0";
            
            [weakSelf setDisplayStr];
            
            weakSelf.footerView.hidden = NO;
                
            [weakSelf.plainTableView.mj_header endRefreshing];
                
                
            [weakSelf.plainTableView reloadData];
           
            
            
            
            
        } else {
            
            
            [weakSelf.plainTableView.mj_header endRefreshing];
            
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
            
            
        }
        
        
    }];
    
 
}


- (void)setDisplayStr{
    
    
    for (GoodsSpecListModel *temp in self.dataModel.spec_list) {
        
        temp.value.firstObject.isSelect = @"1";
       
    }
    
    
    self.dataModel.selectSkuModel = self.dataModel.sku_list.firstObject;
    
//    self.dataModel.price = self.dataModel.sku_list.firstObject.price;
//    
//    self.dataModel.price_rmb = self.dataModel.sku_list.firstObject.price_rmb;
    
    
    self.dataModel.alipay = @"1";
    
    
    NSLog(@"%@",self.dataModel.selectSkuModel.attr_value_items);


    
    
}




#pragma mark - tableviewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.dataModel == nil) {
        return 0;
    } else {
        return 2;
    }
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.dataModel == nil) {
        
        return 0;
    } else {
        
        if (section == 0) {
            return 3;
        } else {
            return 3;
        }
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            KeepCallsTopCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[KeepCallsTopCell identifierStr]];
            
            tableCell.model = self.dataModel;

            
            return tableCell;
        } else if (indexPath.row == 1){
            KeepCallsPhoneCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[KeepCallsPhoneCell identifierStr]];
            
            tableCell.model = self.dataModel;

            return tableCell;
        }else{
            
            KeepCallsSelectCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[KeepCallsSelectCell identifierStr]];
            
            tableCell.model = self.dataModel;
            
            return tableCell;
        }
        
    } else {
        
        if (indexPath.row == 2) {
            
            return [[UITableViewCell alloc]init];
            
        } else {
            
            KeepCallsPayCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[KeepCallsPayCell identifierStr]];
            
            tableCell.index = indexPath;
            
            
            tableCell.detailModel = self.dataModel;
            
            return tableCell;
        }
      
 
    }
    

    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 2) {
            
            NSInteger row = self.dataModel.spec_list.lastObject.value.count;
            
            if (row % 3 == 0) {
                row = row + 0;
            } else if (row % 3 == 1){
                row = row + 2;
            }else{
                
                row = row + 1;
                
            }
             return ((row / 3) + 1) * 54.0;
        } else {
             return 52;
        }
       
    } else {
        
        if (indexPath.row == 2) {
            return 0;
        } else {
            return 72;
        }
        
        
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0;
    } else {
        return 44;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        
        return [[UIView alloc]init];
        
    } else {
        
        KeepCallSectionHeader *view = (KeepCallSectionHeader *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[KeepCallSectionHeader identifierStr]];
        
        return view;
    }
    
    
    
}





- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        [self selectType];
        
    }
    
    
    if (indexPath.section == 1) {
        
        if (indexPath.row == 0) {
            
            if ([self.dataModel.alipay isEqualToString:@"1"]) {
                
                return;
                
            } else {
                
                self.dataModel.alipay = @"1";
                self.dataModel.wechatPay = @"0";
                
            }
            
            
        } else {
            
            if ([self.dataModel.wechatPay isEqualToString:@"1"]) {
                
                return;
                
            } else {
                
                self.dataModel.wechatPay = @"1";
                self.dataModel.alipay = @"0";
                
            }
            
            
        }
        
        [self.plainTableView reloadData];
        
    }
    

}




- (void)selectType{
    
    SelectedListView *view = [[SelectedListView alloc] initWithFrame:CGRectMake(0, 0, 280, 0) style:UITableViewStylePlain];
    
    view.isSingle = YES;
    
    GoodsSpecListModel *temp0 = self.dataModel.spec_list[0];

    NSMutableArray *strM = [NSMutableArray array];
    
    for (int i = 0; i < temp0.value.count; i++) {
        
        [strM addObject:[[SelectedListModel alloc] initWithSid:i Title:temp0.value[i].spec_value_name]];

    }
   
    
    
    
    view.array = strM;
    
    MJWeakSelf;
    view.selectedBlock = ^(NSArray<SelectedListModel *> *array) {
        
        [LEEAlert closeWithCompletionBlock:^{
            
            
            
            
            GoodsSpecListModel *temp = weakSelf.dataModel.spec_list[0];
            
            for (GoodsSpecSubModel *sub in temp.value) {
                
                if ([array.firstObject.title isEqualToString:sub.spec_value_name]) {
                    sub.isSelect = @"1";
                } else {
                    sub.isSelect = @"0";
                }
                
            }
            
     

            
            
            
            
            
            
            NSMutableArray *arrayM = [NSMutableArray array];
            for (GoodsSpecListModel *temp in weakSelf.dataModel.spec_list) {
                NSMutableString *strM = [NSMutableString string];
                for (GoodsSpecSubModel *sub in temp.value) {
                    
                    if ([sub.isSelect isEqualToString:@"1"]) {
                        
                        [strM appendString:sub.spec_id];
                        
                        [strM appendString:@":"];
                        
                        [strM appendString:sub.spec_value_id];
                        
                        [arrayM addObject:strM];
                    }
                }
            }
            
            
            
            
            NSInteger i = 0;
            NSInteger j = arrayM.count;
            for (GoodsSkuListModel *skuModel in weakSelf.dataModel.sku_list) {
                i = 0;
                
                for (NSString *str1 in arrayM) {
                    
                    if ([skuModel.attr_value_items_format containsString:str1]) {
                        i++;
                    }
                    
                }
                
                if (i == j) {
                    weakSelf.dataModel.selectSkuModel = skuModel;
                }
                
            }
            
//            weakSelf.dataModel.price = weakSelf.dataModel.selectSkuModel.price;
//            weakSelf.dataModel.price_rmb = weakSelf.dataModel.selectSkuModel.price_rmb;

            [weakSelf.plainTableView reloadData];

            
            
            NSLog(@"%@",weakSelf.dataModel.selectSkuModel.attr_value_items);

            
            
        }];
        
    };
    
    [LEEAlert alert].config
    .LeeTitle(@"选择供应商")
    .LeeItemInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeCustomView(view)
    .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
    .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeClickBackgroundClose(YES)
    .LeeShow();
    
    
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
